package UI;

import Bean.Employee;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Random;

public class EmployeeManagementSystem extends JFrame{

    // 员工数据字段
    private final String[] columns = { "ID", "姓名", "部门", "职位", "薪资", "入职日期" };
    private final String[] departments = { "技术部", "市场部", "财务部", "人力资源", "销售部" };
    private final String[] positions = { "工程师", "经理", "主管", "分析师", "助理" };
    // 私有成员变量
    private JTextField searchField;     // 搜索框
    private JButton searchButton;       // 搜索按钮
    private JButton addButton;          // 添加按钮
    private JTable employeeTable;       // 表格
    private DefaultTableModel tableModel;   // 表格模型
    private JPopupMenu rowPopupMenu;    // 行菜单
    private static ArrayList< Employee > employees = new ArrayList<>();    // 静态集合，存储员工信息


    public EmployeeManagementSystem(String loginUserName) {
        super(loginUserName+"欢迎使用人事管理系统");
        // 初始化窗口
        initWindow();
        // 创建界面组件
        initComponents();
        // 初始化员工数据
        initEmployeeData();

        this.setVisible(true);
    }


    private void initWindow() {
        setTitle("员工信息管理系统");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示
        setResizable(true);
    }

    // 初始化面板
    private void initComponents() {
        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        mainPanel.setBackground(new Color(240, 245, 249));

        // 顶部搜索面板
        JPanel topPanel = createTopPanel();
        mainPanel.add(topPanel, BorderLayout.NORTH);

        // 中间表格面板
        JPanel centerPanel = createCenterPanel();
        mainPanel.add(centerPanel, BorderLayout.CENTER);

        // 添加主面板到窗口
        add(mainPanel);
    }

    // 创建顶部搜索面板
    private JPanel createTopPanel() {
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        topPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(200, 210, 220)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
                                                             ));
        topPanel.setBackground(new Color(245, 248, 250)); // 浅灰色背景
        topPanel.setOpaque(true);

        // 搜索标签
        JLabel searchLabel = new JLabel("搜索员工:");
        searchLabel.setFont(new Font("黑体", Font.PLAIN, 14));
        searchLabel.setForeground(new Color(70, 70, 70)); // 深灰色文字

        // 搜索框
        searchField = new JTextField(25);
        searchField.setFont(new Font("黑体", Font.PLAIN, 14));
        // 正确创建复合边框
        Border lineBorder = BorderFactory.createLineBorder(new Color(180, 190, 200));
        Border paddingBorder = BorderFactory.createEmptyBorder(8, 10, 8, 10);
        searchField.setBorder(BorderFactory.createCompoundBorder(lineBorder, paddingBorder));
        searchField.setForeground(new Color(60, 60, 60)); // 深灰色文字

        // 搜索按钮 - 修复颜色问题
        searchButton = new JButton("搜索");
        searchButton.setFont(new Font("黑体", Font.BOLD, 14));
        searchButton.setBackground(new Color(70, 130, 180)); // 蓝色背景
        searchButton.setForeground(Color.BLACK); // 黑色文字
        searchButton.setFocusPainted(false);
        searchButton.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 20));
        // 添加按钮 - 修复颜色问题
        addButton = new JButton("添加员工");
        addButton.setFont(new Font("黑体", Font.BOLD, 14));
        addButton.setBackground(new Color(50, 150, 100)); // 绿色背景
        addButton.setForeground(Color.BLACK); // 黑色文字
        addButton.setFocusPainted(false);
        addButton.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 20));
        // 添加到顶部面板
        topPanel.add(searchLabel);
        topPanel.add(searchField);
        topPanel.add(searchButton);
        topPanel.add(addButton);

        return topPanel;
    }

    // 中间面板
    private JPanel createCenterPanel() {
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        centerPanel.setBackground(new Color(240, 245, 249));

        // 创建表格模型
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable( int row, int column ) {
                // 所有单元格不可编辑
                return false;
            }
        };

        // 创建表格
        employeeTable = new JTable(tableModel);
        employeeTable.setFont(new Font("黑体", Font.PLAIN, 13));
        employeeTable.setRowHeight(35);
        employeeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        employeeTable.setGridColor(new Color(220, 230, 240));
        employeeTable.setShowGrid(true);
        employeeTable.setIntercellSpacing(new Dimension(0, 0));
        employeeTable.setFillsViewportHeight(true);

        // 设置表头 - 修复颜色问题
        employeeTable.getTableHeader().setFont(new Font("黑体", Font.BOLD, 14));
        employeeTable.getTableHeader().setBackground(new Color(60, 110, 160)); // 深蓝色背景
        employeeTable.getTableHeader().setForeground(Color.BLACK); // 黑色文字
        employeeTable.getTableHeader().setReorderingAllowed(false);
        // 设置列宽
        TableColumnModel columnModel = employeeTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(60);  // ID
        columnModel.getColumn(1).setPreferredWidth(100); // 姓名
        columnModel.getColumn(2).setPreferredWidth(150); // 部门
        columnModel.getColumn(3).setPreferredWidth(150); // 职位
        columnModel.getColumn(4).setPreferredWidth(100); // 薪资
        columnModel.getColumn(5).setPreferredWidth(120); // 入职日期

        // 添加表格到滚动面板
        JScrollPane scrollPane = new JScrollPane(employeeTable);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 210, 220)));
        scrollPane.getViewport().setBackground(Color.WHITE);

        centerPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建右键菜单
        createRowPopupMenu();

        // 添加鼠标监听器
        employeeTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked( MouseEvent e ) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    int row = employeeTable.rowAtPoint(e.getPoint());
                    if (row >= 0 && row < employeeTable.getRowCount()) {
                        employeeTable.setRowSelectionInterval(row, row);
                        rowPopupMenu.show(employeeTable, e.getX(), e.getY());
                    }
                }
            }
        });

        // 添加按钮事件监听器
        addButton.addActionListener(e -> new AddEmployeesUI());
        searchButton.addActionListener(this::searchEmployees);

        return centerPanel;
    }

    // 创建右键菜单
    private void createRowPopupMenu() {
        rowPopupMenu = new JPopupMenu();
        rowPopupMenu.setBorder(BorderFactory.createLineBorder(new Color(200, 210, 220)));

        // 修改菜单项
        JMenuItem editItem = new JMenuItem("修改员工信息");
        editItem.setFont(new Font("黑体", Font.PLAIN, 13));
        editItem.setForeground(new Color(70, 70, 70));
        editItem.addActionListener(e -> editEmployee());

        // 删除菜单项
        JMenuItem deleteItem = new JMenuItem("删除员工");
        deleteItem.setFont(new Font("黑体", Font.PLAIN, 13));
        deleteItem.setForeground(new Color(180, 50, 50)); // 红色文字
        deleteItem.addActionListener(e -> deleteEmployee());

        rowPopupMenu.add(editItem);
        rowPopupMenu.addSeparator();
        rowPopupMenu.add(deleteItem);
    }

    // 初始化员工数据
    private void initEmployeeData() {
        // 生成20个随机员工数据
        Random rand = new Random();
        for ( int i = 1; i <= 20; i++ ) {
            String id = "E" + String.format("%04d", i);
            String name = generateChineseName();
            String dept = departments[rand.nextInt(departments.length)];
            String position = positions[rand.nextInt(positions.length)];
            String salary = String.format("%.2f", 5000 + rand.nextDouble() * 15000);
            String date = String.format("202%d-%02d-%02d",
                                        rand.nextInt(3) + 1,
                                        rand.nextInt(12) + 1,
                                        rand.nextInt(28) + 1
                                       );

            tableModel.addRow(new Object[] { id, name, dept, position, salary, date });
        }
    }

    private String generateChineseName() {
        String[] surnames = { "张", "王", "李", "赵", "陈", "刘", "杨", "黄", "周", "吴" };
        String[] names = { "伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军",
                "洋", "勇", "艳", "杰", "娟", "涛", "明", "超", "秀兰", "霞" };

        Random rand = new Random();
        return surnames[rand.nextInt(surnames.length)] +
                names[rand.nextInt(names.length)];
    }

    // 编辑员工信息
    private void editEmployee() {
        int selectedRow = employeeTable.getSelectedRow();
        if (selectedRow >= 0) {
            String id = ( String ) tableModel.getValueAt(selectedRow, 0);
            String name = ( String ) tableModel.getValueAt(selectedRow, 1);

            JOptionPane.showMessageDialog(this,
                                          "修改员工: " + name + " (ID: " + id + ")\n\n此功能需要进一步实现",
                                          "修改员工信息",
                                          JOptionPane.INFORMATION_MESSAGE
                                         );
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一个员工", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    // 删除员工
    private void deleteEmployee() {
        int selectedRow = employeeTable.getSelectedRow();
        if (selectedRow >= 0) {
            String id = ( String ) tableModel.getValueAt(selectedRow, 0);
            String name = ( String ) tableModel.getValueAt(selectedRow, 1);

            int confirm = JOptionPane.showConfirmDialog(this,
                                                        "确定要删除员工: " + name + " (ID: " + id + ") 吗?",
                                                        "删除确认",
                                                        JOptionPane.YES_NO_OPTION
                                                       );

            if (confirm == JOptionPane.YES_OPTION) {
                tableModel.removeRow(selectedRow);
                JOptionPane.showMessageDialog(this, "员工 " + name + " 已删除", "删除成功", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一个员工", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    // 搜索员工
    private void searchEmployees( ActionEvent e ) {
        String keyword = searchField.getText().trim();
        if (!keyword.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                                          "搜索关键词: " + keyword + "\n\n搜索功能需要进一步实现",
                                          "搜索结果",
                                          JOptionPane.INFORMATION_MESSAGE
                                         );
        } else {
            JOptionPane.showMessageDialog(this,
                                          "请输入搜索关键词",
                                          "提示",
                                          JOptionPane.WARNING_MESSAGE
                                         );
        }
    }
}